<?php
declare(strict_types=1);

namespace App\Common\Modular\System\Traits;

use App\Common\Modular\System\Model\SeoModel;
use App\Common\Modular\System\Serve\SeoServe;
use Zms\Unit\Str;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Router\Dispatched;

trait SeoParse
{

    /**
     * 获取默认SEO
     * @return array
     */
    public static function defaultSeo(): array
    {
        return container(SeoServe::class)->getDefaultRule();
    }


    /**
     * 解析通过调用方法获取SEO配置
     * @param string $method
     * @param array $param
     * @return array
     */
    public static function methodSeo(string $method, array $param = []): array
    {
        $def = self::defaultSeo();
        /**
         * @var SeoModel $seo
         */
        $seo = SeoModel::where(['sign' => Str::md5_16($method), 'status' => 1])->first();
        if (!$seo) return $def;
        $SeoParse = ['title' => $seo->title ?: $def['title'], 'keywords' => $seo->keywords ?: $def['keywords'], 'description' => $seo->description ?: $def['description']];
        $annotation = container(SeoServe::class)->getMethodSeoAnnotation($method);
        $keys = [];
        if ($annotation) {
            $keys = array_keys($annotation['param']);
        }
        $keys = array_merge(['_title', '_keywords', '_description'], $keys);
        $param['_title'] = $def['title'];
        $param['_keywords'] = $def['keywords'];
        $param['_description'] = $def['description'];
        foreach ($keys as $key) {
            $SeoParse['title'] = str_replace('{' . $key . '}', $param[$key] ?? '', $SeoParse['title']);
            $SeoParse['keywords'] = str_replace('{' . $key . '}', $param[$key] ?? '', $SeoParse['keywords']);
            $SeoParse['description'] = str_replace('{' . $key . '}', $param[$key] ?? '', $SeoParse['description']);
        }
        $SeoParse['title'] = preg_replace("/\{.*\}/", "", $SeoParse['title']);
        $SeoParse['keywords'] = preg_replace("/\{.*\}/", "", $SeoParse['keywords']);
        $SeoParse['description'] = preg_replace("/\{.*\}/", "", $SeoParse['description']);
        return $SeoParse;
    }


    /**
     * 通过路由解析SEO
     * @param array $param
     * @return array
     */
    public static function routerSeo(array $param = []): array
    {
        $callback = container(RequestInterface::class)->getAttribute(Dispatched::class)->handler->callback ?? [];
        if (is_array($callback) && count($callback) === 2) {
            return self::methodSeo($callback[0] . '::' . $callback[1], $param);
        }
        return self::defaultSeo();
    }
}